# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import tools
from odoo import api, fields, models


class InvoiceDetailReport(models.Model):
    _name = "invoice.detail.report"
    _description = "Invoice Detail Report"
    _auto = False
    _order = 'number desc'

    origin = fields.Char(u'源单据(SO号)', readonly=True)
    number = fields.Char(u'发票号码', readonly=True)
    product_id = fields.Many2one('product.product', u'产品', readonly=True)
    partner_id = fields.Many2one('res.partner', u'合作伙伴', readonly=True)
    date_due = fields.Date(u'发票日期', readonly=True)
    quantity = fields.Float(u'开票数量', readonly=True)
    amt_notax = fields.Float(u'发票金额(不含税)', readonly=True)
    amt_tax = fields.Float(u'发票税额', readonly=True)
    amt_taxed = fields.Float(u'发票金额(含税)', readonly=True)

    @api.model_cr
    def init(self):
        tools.drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute("""CREATE or REPLACE VIEW %s as (
SELECT ail.id,
       ai.origin,
       ai.partner_id,
       ai.date_invoice                                    AS date_due,
       ai.number,
       ail.product_id,
       ail.quantity,
       ail.price_subtotal                                 AS amt_notax,
       ail.quantity * ail.price_unit                      AS amt_taxed,
       ail.quantity * ail.price_unit - ail.price_subtotal AS amt_tax
FROM account_invoice ai
       INNER JOIN account_invoice_line ail ON ai.id = ail.invoice_id
       LEFT JOIN account_invoice_line_tax ailt ON ail.id = ailt.invoice_line_id
       LEFT JOIN account_journal aj ON ai.journal_id = aj.id
WHERE ai.state IN ('open', 'paid')
  AND ai.type IN ('out_invoice', 'out_refund')
  AND aj.type = 'sale'
            )""" % self._table)
